package ru.ipo.dces.plugins.admin.packetregistration;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

public class PasswordCreator {

    public static char[] getPassword(int length) {
        String hash;
        char[] charset = new char[26 + 26 + 10];

        int i = 0;
        for (char ch = 'a'; ch <= 'z'; ch++, i++)
            charset[i] = ch;
        for (char ch = 'A'; ch <= 'Z'; ch++, i++)
            charset[i] = ch;
        for (char ch = '0'; ch <= '9'; ch++, i++)
            charset[i] = ch;

        try {
            hash = MD5(new String(new SecureRandom().generateSeed(length)));
        } catch (NoSuchAlgorithmException e) {
            return new char[] {};
        }

        if (length > hash.length())
            return new char[] {};
//        System.out.println("hash = " + new String(hash.toCharArray()));
//        System.out.println("charset = " + new String(charset));
        char[] password = new char[length];
        for (i = 0; i < length; i++) {
            int index = hash.toCharArray()[i] % charset.length;
            password[i] = charset[index];
        }

        return password;
    }

    /**
     * Turns array of bytes into string representing each byte as
     * unsigned hex number.
     *
     * @param hash Array of bytes to convert to hex-string
     * @return Generated hex string
     */
    private static String ByteToHexString(byte hash[]) {
        StringBuffer buf = new StringBuffer(hash.length * 2);
        int i;
        for (i = 0; i < hash.length; i++) {
            if ((hash[i] & 0xff) < 0x10)
                buf.append("0");
            buf.append(Long.toString(hash[i] & 0xff, 16));
        }
        return buf.toString();
    }

    private static String digest(String input, String algorithm) throws NoSuchAlgorithmException {
        // Calculate Hash from input
        MessageDigest md = MessageDigest.getInstance(algorithm);
        // Convert byte array hash to string
        return ByteToHexString(md.digest(input.getBytes()));
    }

    /**
     * Calculate RSA/MD5 hash from input string and return result as string
     *
     * @param input String to calculate hash
     * @return Generated MD5 string
     * @throws java.security.NoSuchAlgorithmException
     */
    public static String MD5(String input) throws NoSuchAlgorithmException {
        return digest(input, "MD5");
    }

    public static void main(String[] args) {
        String outer = String.valueOf(getPassword(10));
        System.out.println("pass = " + outer);
    }
}